import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';

import '../tagView/kq_icon_tag.dart';

enum FlowType {
  ///左图右文本样式
  iconTextFlowType,

  ///左文本右文本样式
  textTextFlowType,

  ///左文本右图样式
  textIconFlowType
}

class KqWrapFlow extends StatefulWidget {
  ///一行个数
  final int crossAxisCount;

  /// 个数
  final int Function()? totalCountCallback;

  ///当前是否需要显示，如果false，则终止，负责一直会加载 比重
  final bool Function(int index)? needDrawCallback;

  ///Text行数
  final int Function(int index) renderTextMaxLineCallback;

  ///流样式
  final FlowType? flowType;

  ///水平方向item间距
  final double? spacing;

  ///竖直方向item间距
  final double? runSpacing;

  ///左边item的宽度,icon 宽度==高度
  final double? leftItemMaxWidth;

  ///背景色,默认白色
  final Color? backgroundColor;

  ///左边文本颜色,默认：text333
  final Color? leftTextColor;

  ///右边文本颜色，默认：text666
  final Color? textColor;

  ///左边文本文字大小 ,默认：14
  final double? leftFont;

  ///文案大小默认14
  final double? fontSize;

  ///icon
  final String Function(int index)? renderIconPathCallback;

  ///left Text
  final String Function(int index)? renderLeftTextCallback;

  ///right Text
  final String Function(int index)? renderRightTextCallback;

  ///设置宽度比例，一行item比例总和最大等于1,如果一行的item宽度等分，则不实现该回调，
  final double Function(int index, int crossAxisIndex)? itemWithRaleCallback;

  ///设置宽度，如果一行的item宽度等分，则不实现该回调，
  final double Function(int index, int crossAxisIndex)? itemWithWidthCallback;

  ///设置辅轴对其方式 默认：center
  final CrossAxisAlignment Function(int index, int crossAxisIndex)?
      crossAxisCallback;

  ///设置主轴对其方式 默认：start
  final MainAxisAlignment Function(int index, int crossAxisIndex)?
      mainAxisCallback;

  const KqWrapFlow(
      {Key? key,
      required this.crossAxisCount,
      required this.renderTextMaxLineCallback,
      this.needDrawCallback,
      this.totalCountCallback,
      this.flowType = FlowType.iconTextFlowType,
      this.spacing = 4,
      this.runSpacing = 9,
      this.leftItemMaxWidth,
      this.backgroundColor,
      this.leftTextColor,
      this.textColor,
      this.leftFont,
      this.fontSize,
      this.renderIconPathCallback,
      this.renderLeftTextCallback,
      this.renderRightTextCallback,
      this.itemWithRaleCallback,
      this.itemWithWidthCallback,
      this.crossAxisCallback,
      this.mainAxisCallback})
      : assert((flowType == FlowType.iconTextFlowType &&
                renderIconPathCallback != null &&
                renderRightTextCallback != null) ||
            (flowType == FlowType.textTextFlowType &&
                renderLeftTextCallback != null &&
                renderRightTextCallback != null) ||
            (flowType == FlowType.textIconFlowType &&
                renderLeftTextCallback != null &&
                renderIconPathCallback != null)),
        super(key: key);

  @override
  State<KqWrapFlow> createState() => _KqWrapFlowState();
}

class _KqWrapFlowState extends State<KqWrapFlow> {
  final GlobalKey _wrapKey = GlobalKey();
  double widgetWidth = 0;
  //默认设置100
  double itemWidth = 0;

  @override
  void initState() {
    super.initState();
    //监听widget绘制完成，计算每个item的宽度
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final RenderBox? supperView =
          _wrapKey.currentContext!.findRenderObject() as RenderBox?;
      var size = supperView?.size;
      //获取Row的宽度
      widgetWidth = size?.width ?? 0;
      //如果不设置item所占比例,则不计算item宽度
      if (widget.itemWithRaleCallback == null) {
        itemWidth = getItemContainerWidth() / widget.crossAxisCount;
      } else if (widget.itemWithWidthCallback == null) {
        itemWidth = getItemContainerWidth() / widget.crossAxisCount;
      }
      setState(() {});
    });
  }

  double getItemContainerWidth() {
    //每个item的宽度=Row的宽度-每个item的间距(widget.spacing * (widget.crossAxisCount - 1))-容错(可能小数点后面位数太多导致超屏(widget.crossAxisCount - 1))
    var width = (widgetWidth -
        widget.spacing! * (widget.crossAxisCount - 1) -
        (widget.crossAxisCount - 1));
    if (width > 0) {
      return width;
    }
    return widgetWidth;
  }

  List<Widget> renderItems() {
    List<Widget> items = [];
    Map<int, double> widthData = {};
    int toatal = 10000;
    if (widget.totalCountCallback != null) {
      toatal = widget.totalCountCallback!();
    }
    for (var i = 0; i < toatal; i++) {
      bool isShow = true;
      if (widget.totalCountCallback == null &&
          widget.needDrawCallback != null) {
        isShow = widget.needDrawCallback!(i);
      }
      bool isNextLast = true;
      if (widget.totalCountCallback == null &&
          widget.needDrawCallback != null) {
        isNextLast = widget.needDrawCallback!(i + 1);
      } else if (widget.totalCountCallback != null && i + 1 >= toatal) {
        isNextLast = false;
      }
      if (isShow) {
        double viewWidth = itemWidth;
        if (widget.itemWithRaleCallback != null ||
            widget.itemWithWidthCallback != null) {
          if (i % widget.crossAxisCount < widget.crossAxisCount) {
            if (isNextLast &&
                i % widget.crossAxisCount != widget.crossAxisCount - 1) {
              //不是最后一个或不是一行的最后一个
              if (widget.itemWithRaleCallback != null) {
                //根据比例来计算每个item的width
                double rale =
                    widget.itemWithRaleCallback!(i, i % widget.crossAxisCount);
                viewWidth = getItemContainerWidth() * rale;
              } else if (widget.itemWithWidthCallback != null) {
                //获取每个item的宽度
                viewWidth =
                    widget.itemWithWidthCallback!(i, i % widget.crossAxisCount);
              }
            } else {
              //最后一个item或者是每一行的最后一个
              int index = i % widget.crossAxisCount;
              double totalToLast = 0;
              if (index == 0) {
                viewWidth = getItemContainerWidth();
              } else {
                for (var index = i - widget.crossAxisCount;
                    index < i;
                    index++) {
                  if (index % widget.crossAxisCount <
                      i % widget.crossAxisCount) {
                    if (widthData.length > index && widthData[index] != null) {
                      totalToLast = totalToLast + widthData[index]!;
                    }
                  }
                }
                //宽度=widgetWidth-前面item宽度的和-容错（widget.crossAxisCount -1）
                viewWidth = getItemContainerWidth() -
                    totalToLast -
                    widget.crossAxisCount -
                    1;
              }
              if (viewWidth < 0) {
                viewWidth = 0;
              }
            }
            widthData[i] = viewWidth;
          }
        }
        CrossAxisAlignment crossAxist = CrossAxisAlignment.center;
        MainAxisAlignment mainAxist = MainAxisAlignment.start;
        if (widget.crossAxisCallback != null) {
          crossAxist = widget.crossAxisCallback!(i, i % widget.crossAxisCount);
        }
        if (widget.mainAxisCallback != null) {
          mainAxist = widget.mainAxisCallback!(i, i % widget.crossAxisCount);
        }
        if (widget.flowType == FlowType.iconTextFlowType) {
          String iconPath = widget.renderIconPathCallback!(i);
          String text = widget.renderRightTextCallback!(i);
          int lines = widget.renderTextMaxLineCallback(i);
          items.add(
            KqIconTagView(
              iconPath: iconPath,
              crossAxisAlignment: crossAxist,
              mainAxisAlignment: mainAxist,
              text: text,
              maxLines: lines,
              viewType: 1,
              iconWidth: widget.leftItemMaxWidth,
              width: viewWidth,
              fontSize: widget.fontSize,
              textColor: widget.textColor,
              backgroundColor: widget.backgroundColor,
            ),
          );
        } else if (widget.flowType == FlowType.textTextFlowType) {
          String rightText = widget.renderRightTextCallback!(i);
          String leftText = widget.renderLeftTextCallback!(i);
          int lines = widget.renderTextMaxLineCallback(i);
          items.add(
            KqIconTagView(
              iconPath: '',
              crossAxisAlignment: crossAxist,
              mainAxisAlignment: mainAxist,
              text: rightText,
              leftText: leftText,
              maxLines: lines,
              viewType: 3,
              iconWidth: widget.leftItemMaxWidth,
              width: viewWidth,
              fontSize: widget.fontSize,
              leftFont: widget.leftFont,
              leftTextColor: widget.leftTextColor,
              textColor: widget.textColor,
              backgroundColor: widget.backgroundColor,
            ),
          );
        } else if (widget.flowType == FlowType.textIconFlowType) {
          String text = widget.renderLeftTextCallback!(i);
          String iconPath = widget.renderIconPathCallback!(i);
          int lines = widget.renderTextMaxLineCallback(i);
          items.add(
            KqIconTagView(
              iconPath: iconPath,
              crossAxisAlignment: crossAxist,
              mainAxisAlignment: mainAxist,
              text: text,
              leftText: text,
              maxLines: lines,
              viewType: 2,
              iconWidth: widget.leftItemMaxWidth,
              width: itemWidth,
              fontSize: widget.fontSize,
              leftTextColor: widget.leftTextColor,
              textColor: widget.textColor,
              backgroundColor: widget.backgroundColor,
            ),
          );
        }
      } else {
        //终止
        break;
      }
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      key: _wrapKey,
      children: [
        Expanded(
            child: Wrap(
          spacing: widget.spacing ?? 4,
          runSpacing: widget.runSpacing ?? 9.r,
          children: renderItems(),
        ))
      ],
    );
  }
}
